﻿using ConsoleApplication.WebAPI;
using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace HM
{
    [HotUpdate]
    [Description("聚合账核销结果，直接调拨单自动下推销售出库单")]
    public class DBPushSalOut : IScheduleService
    {
        public void Run(Context ctx, Schedule schedule)
        {
            try
            {
                var result = InvokeHelper.Login();
                var iResult = JObject.Parse(result)["LoginResultType"].Value<int>();
                if (iResult == 1)
                {
                    string F_RXWU_Text6 = "", FEntryId = "", FBILLNO = "", F_RXWU_Date2 = "", FMATERIALID = "", DBfentryid = "", F_RXWU_DATE = "", MATERIAL = "", F_RXWU_Text2 = "";
                    //string SQL = "/*dialect*/" + string.Format(@"select * from view_CRKDB");
                    //DynamicObjectCollection DynamData = DBUtils.ExecuteDynamicObject(ctx, SQL);
                    //if (DynamData.Count > 0)
                    //{
                    //    for (int i = 0; i < DynamData.Count; i++)
                    //    {
                            
                            string SQL0 = "/*dialect*/" + string.Format(@"select * from (
                            select t1.fentryid DBfentryid,t10.FNUMBER MATERIAL,T.F_RXWU_Text2 from T_STK_STKTRANSFERIN t
                            left join T_STK_STKTRANSFERINENTRY t1 on t.fid=t1.fid
                            Left join T_BD_MATERIAL t10 on t1.FMATERIALID=t10.FMATERIALID
							left join T_STK_STKTRANSFERINENTRY_R t3 on t1.FENTRYID=t3.FENTRYID
                            WHERE FBizType<>'DRPTRANS'
							and t1.F_RXWU_QTY2=0
							and t.F_RXWU_Text2<>''
							AND T.FCREATORID='16394'
							and t.FDATE>='2023-08-01'
							)T
							LEFT JOIN view_CRKDB T1 ON T.MATERIAL=T1.FMATERIALID AND T.F_RXWU_TEXT2=T1.F_RXWU_Text6
							WHERE T1.FMATERIALID IS not  NULL");
                            DynamicObjectCollection DynamData0 = DBUtils.ExecuteDynamicObject(ctx, SQL0);
                            if (DynamData0.Count > 0)
                            {
                                for (int k = 0; k < DynamData0.Count; k++)
                                {
                                    DBfentryid = Convert.ToString(DynamData0[k]["DBfentryid"]);
                                    MATERIAL = Convert.ToString(DynamData0[k]["MATERIAL"]);
                                    F_RXWU_Text2 = Convert.ToString(DynamData0[k]["F_RXWU_Text2"]);
                                    //获取已核销、到账时间不为空并且没有退货的平台单号
                                    F_RXWU_Date2 = Convert.ToString(DynamData0[k]["F_RXWU_Date2"]);
                                    F_RXWU_DATE = Convert.ToString(DynamData0[k]["F_RXWU_DATE"]);
                                    F_RXWU_Text6 = Convert.ToString(DynamData0[k]["F_RXWU_Text6"]);
                                    FMATERIALID = Convert.ToString(DynamData0[k]["FMATERIALID"]);
                                    FEntryId = Convert.ToString(DynamData0[k]["FEntryId"]);

                                        string json = "{\"Ids\":\"\",\"Numbers\":[],\"EntryIds\":\"" + DBfentryid + "\",\"RuleId\":\"TransferDirect-OUTSTOCK\",\"TargetBillTypeId\":\"\",\"TargetOrgId\":0,\"TargetFormId\":\"SAL_OUTSTOCK\",\"IsEnableDefaultRule\":\"false\",\"IsDraftWhenSaveFail\":\"false\",\"CustomParams\":{}}";
                                        result = InvokeHelper.Push("STK_TransferDirect", json.ToString());
                                        JObject jobject = JObject.Parse(result);
                                        string a = Convert.ToString(jobject["Result"]["ResponseStatus"]["IsSuccess"]);
                                        bool IsSuccess = a == "True";
                                        if (IsSuccess)
                                        {
                                            string SQL1 = "/*dialect*/" + string.Format(@"update RXWU_t_Cust_Entry100013 set F_RXWU_COMBO='1' where FEntryId='{0}'", FEntryId);
                                            DBUtils.Execute(ctx, SQL1);
                                            Log.WriteLog("直接调拨单自动下推销售出库单成功", "报文:" + json.ToString() + "/r/n" + "返回结果:" + result.ToString() + "ctx:" + ctx);
                                            var SuccessEntitysId = jobject["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Id"];
                                            if (Convert.ToDateTime(F_RXWU_DATE) < Convert.ToDateTime(F_RXWU_Date2) && (!F_RXWU_Date2.Equals("") || !F_RXWU_Date2.Equals("NULL") || !F_RXWU_Date2.Equals(" ")))
                                            {
                                                string SQL2 = "/*dialect*/" + string.Format(@"update T_SAL_OUTSTOCK set FDATE='{1}' where FID='{0}'", SuccessEntitysId, F_RXWU_Date2);
                                                DBUtils.Execute(ctx, SQL2);
                                            }
                                            else
                                            {
                                                string SQL2 = "/*dialect*/" + string.Format(@"update T_SAL_OUTSTOCK set FDATE='{1}' where FID='{0}'", SuccessEntitysId, F_RXWU_DATE);
                                                DBUtils.Execute(ctx, SQL2);
                                            }
                                            string Submit = "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\"" + SuccessEntitysId + "\",\"SelectedPostId\":0,\"NetworkCtrl\":\"\",\"IgnoreInterationFlag\":\"\"}";
                                            result = InvokeHelper.Submit("SAL_OUTSTOCK", Submit);
                                            string Audit = "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\"" + SuccessEntitysId + "\",\"InterationFlags\":\"\",\"NetworkCtrl\":\"\",\"IsVerifyProcInst\":\"\",\"IgnoreInterationFlag\":\"\"}";
                                            result = InvokeHelper.Audit("SAL_OUTSTOCK", Audit);
                                        }
                                        else
                                        {
                                            Log.WriteLog("直接调拨单自动下推销售出库单失败", "报文:" + json.ToString() + "/r/n" + "返回结果:" + result.ToString() + "ctx:" + ctx);
                                            string SQL1 = "/*dialect*/" + string.Format(@"update RXWU_t_Cust_Entry100013 set F_RXWU_COMBO='0' where FEntryId='{0}'", FEntryId);
                                            DBUtils.Execute(ctx, SQL1);
                                        }
                                    }
                                }
                            }
                        }
            //    }
            //}
            catch (Exception ex)
            {
                Log.WriteLog("直接调拨单自动下推销售出库单程序报错", "原因:" + ex.ToString() + "ctx:" + ctx);
            }
        }
    }
}
